package com.kiln.juxingqs.ui.kchart

import android.content.Intent
import android.os.Handler
import androidx.appcompat.app.AppCompatDelegate
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import com.blankj.utilcode.util.LogUtils
import com.github.tifezh.kchartlib.chart.view.KChartView
import com.google.android.material.tabs.TabLayout
import com.kiln.juxingqs.BaseMiddleActivity
import com.kiln.juxingqs.R
import com.kiln.juxingqs.adapter.chart.SimpleFragmentPagerAdapter
import com.kiln.juxingqs.api.bean.KLineHead
import com.kiln.juxingqs.databinding.ActivityStockDetailBinding
import com.kiln.juxingqs.fragment.market.Chart30MoreKLineFragment
import com.kiln.juxingqs.fragment.market.Chart7MoreKLineFragment
import com.kiln.juxingqs.fragment.market.ChartFiveDayFragment
import com.kiln.juxingqs.fragment.market.ChartMinuteMoreKLineFragment
import com.kiln.juxingqs.fragment.market.ChartMoreKLineFragment
import com.kiln.juxingqs.fragment.market.ChartOneDayFragment
import com.kiln.juxingqs.ui.SyDetailActivity
import com.kiln.juxingqs.ui.vm.KLineModel
import com.kiln.juxingqs.utils.cache.ACache

/**
 * Description K线图
 * Author puyantao
 * Email 1067899750@qq.com
 * Date 2018-11-30 10:27
 */
class StockDetailActivity : BaseMiddleActivity<KLineModel, ActivityStockDetailBinding>() {

    var kchartView: KChartView? = null

    open var goodsId: String? = null
    var zd_float: String? = null
    var curPos: Int = 0
    val handler = Handler()
    private var aCache: ACache? = null

    override fun getLayout(): Int = R.layout.activity_stock_detail

    override fun initViewModel(): KLineModel = createViewModel()

    override fun initView() {
        super.initView()
        binding.event = this
        binding.vm = viewModel

        goodsId = intent.getStringExtra("goodsId")!!
        zd_float = intent.getStringExtra("zd_float")!!

        aCache = ACache.get(this)
//        handler.postDelayed(runnable, 0) //每几秒执行一次runnable. -第二步
//        AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)

        initVp()
        setVpListener()

        getHeadGoodData()
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        initView()
    }

    private fun setVpListener() {
        binding.tab.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
            override fun onTabSelected(tab: TabLayout.Tab) {
                var pos: Int = tab.position
                curPos = pos

            }

            override fun onTabUnselected(tab: TabLayout.Tab?) {}
            override fun onTabReselected(tab: TabLayout.Tab?) {}
        })

        binding.llScreenChange.setOnClickListener {
            startActivity(Intent(this, StockDetailLandActivity::class.java).apply {
                putExtra("goodsId", "${goodsId}")
                putExtra("zd_float", "${zd_float}")
                putExtra("landscape", true)
            })
            finish()
        }
    }

    private fun initVp() {
//        val fragmentList = arrayOf<Fragment>(
//            ChartOneDayFragment.newInstance(false, goodsId!!)!!,
//            ChartKLineMinute1Fragment.newInstance(5, false, goodsId!!),
//            ChartFiveDayFragment.newInstance(false, goodsId!!)!!,
//            ChartMoreKLineFragment.newInstance(1, false, goodsId!!),
//            ChartKLine7Fragment.newInstance(7, false, goodsId!!),
//            ChartKLine30Fragment.newInstance(30, false, goodsId!!),
//
////            ChartKLineMinute5Fragment.newInstance(5, false, goodsId!!),
//        )
        val fragmentList = arrayOf<Fragment>(
            ChartOneDayFragment.newInstance(false, goodsId!!)!!,
            ChartMinuteMoreKLineFragment.newInstance(5, false, goodsId!!),
//            ChartFiveDayFragment.newInstance(false, goodsId!!)!!,
            ChartMoreKLineFragment.newInstance(1, false, goodsId!!),
            Chart7MoreKLineFragment.newInstance(7, false, goodsId!!),
            Chart30MoreKLineFragment.newInstance(30, false, goodsId!!),
        )
//        val titles = arrayOf("分时", "1分", "五日", "日K", "周K", "月K") //, "5分"
        val titles = arrayOf("分时", "1分", "日K", "周K", "月K") //, "5分"
        var adapter = SimpleFragmentPagerAdapter(supportFragmentManager, fragmentList, titles)
        binding.viewPager.adapter = adapter
        binding.viewPager.setOffscreenPageLimit(fragmentList.size)
        binding.tab.setupWithViewPager(binding.viewPager)
    }

//    val runnable: Runnable = object : Runnable {
//        override fun run() {
////            //要做的事情
//            if (DateUtils.isBelong(viewModel.begin_time, viewModel.end_time)) {
//                //实时刷新
//                viewModel.holeKLineHead(goodsId)
//                if (curPos == 0) { //分时
//                    viewModel.kType.value = 0
//                    viewModel.holeOneDay(goodsId!!)
//                } else if (curPos == 2) { //五日
//                    viewModel.kType.value = 1
//                    viewModel.hole5Day(goodsId!!)
//                }
//                viewModel.isOpenTime.value = true
//                LogUtils.i("在${viewModel.begin_time} - ${viewModel.end_time}，时间范围内")
//            } else {
////                LogUtils.i("非开盘时间范围内")
//                viewModel.isOpenTime.value = false
//            }
//            handler.postDelayed(this, 5000) //每5秒执行一次runnable. -第一步
//        }
//    }

    private fun getHeadGoodData() {
        viewModel.holdGoodDetail(goodsId!!)
    }

    override fun observerUI() {
        super.observerUI()
        viewModel.goodsDetail.observe(this, {
            it?.let {
                if (it.isSuccess && it.data != null) {
                    binding.bean = it.data
                    binding.zdFloat = zd_float

                    if (zd_float!!.startsWith("+")) {
                        binding.tvZdf.setTextColor(ContextCompat.getColor(this, R.color.priceRed2))
                    } else if (zd_float!!.startsWith("-")) {
                        binding.tvZdf.setTextColor(ContextCompat.getColor(this, R.color.lightGreen))
                    } else {
                        binding.tvZdf.setTextColor(ContextCompat.getColor(this, R.color.grey))
                    }
                }
            }
        })

        viewModel.callkLineHead.observe(this, {
            it?.let {
                if (it.isSuccess) {
                    fillHeader(it.data?.goods_info as KLineHead.GoodsInfo)
                    viewModel.callkLineHead.value = null
                }
            }
        })

    }

    private fun fillHeader(head: KLineHead.GoodsInfo) {
        binding.apply {
            tvCjPrice.text = head.price
            if (head.zd_float.startsWith("+")) {
                tvCjPrice.setTextColor(ContextCompat.getColor(this@StockDetailActivity, R.color.priceRed2))
                tvWhat.setTextColor(ContextCompat.getColor(this@StockDetailActivity, R.color.priceRed2))
            } else if (head.zd_float.startsWith("-")) {
                tvCjPrice.setTextColor(ContextCompat.getColor(this@StockDetailActivity, R.color.lightGreen))
                tvWhat.setTextColor(ContextCompat.getColor(this@StockDetailActivity, R.color.lightGreen))
            } else {
                tvCjPrice.setTextColor(ContextCompat.getColor(this@StockDetailActivity, R.color.grey))
                tvWhat.setTextColor(ContextCompat.getColor(this@StockDetailActivity, R.color.grey))
            }
            tvWhat.text = "${head.zd_price}" + "\t\t" + "${head.zd_float}"
            tvCjNum.text = head.buy_sell_num
            tvCjE.text = head.buy_sell_price
        }
    }

    fun goSyDetail() {
        startActivity(Intent(this, SyDetailActivity::class.java).apply {
            putExtra("goodsId", "${goodsId}")
        })
    }

    override fun onRestart() {
        super.onRestart()
        LogUtils.i("onRestart")
//        handler.postDelayed(runnable, 0) //每几秒执行一次runnable. -第二步
    }

    override fun onPause() {
        super.onPause()
//        handler.removeCallbacksAndMessages(null)
        LogUtils.i("onPause")
    }

    override fun onStop() {
        super.onStop()
        LogUtils.i("onStop")
    }

    override fun onDestroy() {
        super.onDestroy()
//        handler.removeCallbacks(runnable);
//        handler.removeCallbacksAndMessages(null)
    }

}